﻿using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Hosting;

namespace heyirunde.variable
{
    public class SteHelper
    {
        public static string rootPath = HostingEnvironment.MapPath("~/");      //主要用在其他地方

        private Dictionary<string, Object> _dic;
        private HttpContext _context;
        public string imageUrl = ConfigurationManager.AppSettings["ImageUrl"];     //服务器地址，用于获取完整的图片地址

        public Dictionary<string, Object> Dic
        {
            get { return _dic; }
            set { _dic = value; }
        }

        /// <summary>
        /// 判断数组中的元素对应的传入的参数是否为空
        /// </summary>
        /// <param name="str"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool Check(string[] str)
        {
            foreach (string s in str)
            {
                if (string.IsNullOrEmpty(_context.Request.Form[s]))
                {
                    return true;
                }
            }
            return false;
        }

        public string AddStr(string s)
        {
            return _context.Request.Form[s];
        }

        public int AddInt32(string s)
        {
            if (string.IsNullOrEmpty(_context.Request.Form[s]))
            {
                return 0;
            }
            return Convert.ToInt32(_context.Request.Form[s]);
        }

        public DateTime AddDateTime(string s)
        {
            return Convert.ToDateTime(_context.Request.Form[s]);
        }

        /// <summary>
        /// 如果传入的为空字符串，默认返回1970年
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public DateTime AddDateTimeAuto(string s)
        {
            if (string.IsNullOrEmpty(_context.Request.Form[s].Trim()))
            {
                return Convert.ToDateTime("1970-01-01");
            }
            else
            {
                return Convert.ToDateTime(_context.Request.Form[s]);
            }
        }



        /// <summary>
        /// 生成 Json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string ObjToJson(Object obj)
        {
            StringWriter sw;
            JsonSerializer serializer = new JsonSerializer();
            sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), obj);
            return sw.GetStringBuilder().ToString();
        }
        //返回Json信息
        public void RebackJson(Object obj)
        {
            string s = ObjToJson(obj);
            _context.Response.Write(s);
        }


        /// <summary>
        /// 基于Sha1的自定义加密字符串方法：输入一个字符串，返回一个由40个字符组成的十六进制的哈希散列（字符串）。（x2：字母小写，X2字母大写）
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <returns>加密后的十六进制的哈希散列（字符串）</returns>
        public string Sha1(string str)
        {
            var buffer = Encoding.UTF8.GetBytes(str);
            var data = SHA1.Create().ComputeHash(buffer);

            var sb = new StringBuilder();
            foreach (var t in data)
            {
                sb.Append(t.ToString("x2"));
            }

            return sb.ToString();
        }


        //返回固定的json信息
        public void RebackStaJson(JsonMessage code)
        {
            if (code == JsonMessage.NotNull)
            {
                RebackJson(new { status = 201, msg = "参数不能为空！" });
            }
            else if (code == JsonMessage.NoPower)
            {
                RebackJson(new { status = 203, msg = "没有该权限！" });
            }
            else if (code == JsonMessage.NoObject)
            {
                RebackJson(new { status = 221, msg = "没有找到该实例！" });
            }
        }

        /// <summary>
        /// 分隔字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static List<string> StrToList(string str, char c)
        {
            List<string> list = new List<string>();
            string[] arr = str.Split(c);
            foreach (string s in arr)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    list.Add(s);
                }
            }
            return list;
        }

        public static List<string> StrToList(string str)
        {
            List<string> list = new List<string>();
            string[] arr = str.Split(new char[] { ',', ';' });
            foreach (string s in arr)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    list.Add(s);
                }
            }
            return list;
        }

        public static List<int> StrToListInt(string str)
        {
            List<int> list = new List<int>();
            string[] arr = str.Split(new char[] { ',', ';' });
            foreach (string s in arr)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    list.Add(Convert.ToInt32(s));
                }
            }
            return list;
        }

        public static string ListToStr(List<string> ls)
        {
            string result = "";
            foreach (string s in ls)
            {
                result = result + s + ";";
            }
            return result;
        }

        //去除字段后的空格或返回空字符串
        public string TrimField(string s)
        {
            if (s == null)
            {
                return "";
            }
            else
            {
                return s.Trim();
            }
        }

        /// <summary>
        /// 获取单张图片的地址
        /// </summary>
        /// <param name="picAddr">图片的相对路径</param>
        /// <returns></returns>
        public string GetSinglePicAddr(string picAddr)
        {
            //string imageUrl = ConfigurationManager.AppSettings["ImageUrl"];     //服务器地址

            if (picAddr == null)
            {
                return "";
            }
            else
            {
                if (picAddr.Trim() == "" || picAddr.Trim() == "0")
                {
                    return "";
                }
                else
                {
                    return imageUrl + picAddr;
                }
            }
        }
        /// <summary>
        /// 获取请求的value
        /// </summary>
        /// <returns></returns>
        public List<string> GetRequestFormValue()
        {
            List<string> values = new List<string>();

            for (int i = 0; i < _context.Request.Form.Count; i++)
            {
                values.Add(_context.Request.Form[i]);
            }

            return values;
        }
    }

    /// <summary>
    /// 枚举：返回的json信息
    /// </summary>
    public enum JsonMessage
    {
        /// <summary>
        /// 201：参数不能为空！
        /// </summary>
        NotNull,
        /// <summary>
        /// 203：没有该权限
        /// </summary>
        NoPower,
        /// <summary>
        /// 221：没有找到该实例！
        /// </summary>
        NoObject

    }
}